"""
MCP会话模型

用于存储MCP会话信息，包括连接状态、配置等
"""

from sqlalchemy import Column, String, Boolean, Integer, DateTime, JSON, Text, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database import Base
import enum


class SessionStatus(str, enum.Enum):
    """会话状态枚举"""
    CONNECTING = "connecting"
    CONNECTED = "connected"
    DISCONNECTED = "disconnected"
    ERROR = "error"


class MCPSession(Base):
    """
    MCP会话表
    
    存储MCP WebSocket会话的基本信息和状态
    """
    __tablename__ = "mcp_sessions"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment="主键")
    
    # 用户关联
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True, comment="用户ID")
    
    # 会话信息
    session_id = Column(String(128), unique=True, nullable=False, index=True, comment="MCP会话ID（UUID）")
    mcp_server_url = Column(String(512), nullable=False, comment="MCP服务器地址")
    
    # 关联关系
    conversation_id = Column(Integer, ForeignKey("conversations.id", ondelete="SET NULL"), nullable=True, comment="关联的对话ID")
    model_config_id = Column(Integer, ForeignKey("model_configs.id", ondelete="SET NULL"), nullable=True, comment="关联的模型配置ID")
    
    # 状态信息
    status = Column(
        Enum(SessionStatus),
        default=SessionStatus.CONNECTING,
        nullable=False,
        index=True,
        comment="会话状态"
    )
    is_active = Column(Boolean, default=True, nullable=False, index=True, comment="是否活跃")
    
    # 配置信息
    connection_config = Column(JSON, comment="连接配置（超时、重试等）")
    
    # 统计信息
    message_count = Column(Integer, default=0, nullable=False, comment="消息总数")
    error_count = Column(Integer, default=0, nullable=False, comment="错误次数")
    last_heartbeat_at = Column(DateTime(timezone=True), comment="最后心跳时间")
    
    # 时间戳
    connected_at = Column(DateTime(timezone=True), comment="连接建立时间")
    disconnected_at = Column(DateTime(timezone=True), comment="断开连接时间")
    expires_at = Column(DateTime(timezone=True), comment="过期时间")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间")
    
    # 关系
    user = relationship("User", back_populates="mcp_sessions")
    contexts = relationship("MCPContext", back_populates="session", cascade="all, delete-orphan")
    messages = relationship("MCPMessage", back_populates="session", cascade="all, delete-orphan")
    conversation = relationship("Conversation", foreign_keys=[conversation_id])
    model_config = relationship("ModelConfig", foreign_keys=[model_config_id])
    
    def __repr__(self):
        return f"<MCPSession(id={self.id}, session_id={self.session_id}, status={self.status})>"

